<template>
  <div class="user-center">
    <el-row :gutter="20">
      <!-- 左侧用户信息卡片 -->
      <el-col :span="6">
        <el-card class="user-info-card">
          <div class="user-avatar">
            <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar"></el-avatar>
          </div>
          <div class="user-details">
            <h2>{{ userInfo.username }}</h2>
            <p>{{ userInfo.email }}</p>
            <el-button type="text" @click="showEditDialog = true">
              <i class="el-icon-edit"></i> 编辑资料
            </el-button>
          </div>
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-value">{{ orderStats.total || 0 }}</div>
              <div class="stat-label">总订单</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ orderStats.pending || 0 }}</div>
              <div class="stat-label">待支付</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ orderStats.completed || 0 }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧订单列表 -->
      <el-col :span="18">
        <el-card>
          <div slot="header" class="clearfix">
            <span>我的订单</span>
            <el-radio-group v-model="orderStatus" size="small" @change="handleStatusChange">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button label="PENDING">待支付</el-radio-button>
              <el-radio-button label="PAID">已支付</el-radio-button>
              <el-radio-button label="COMPLETED">已完成</el-radio-button>
              <el-radio-button label="CANCELLED">已取消</el-radio-button>
            </el-radio-group>
          </div>

          <!-- 订单列表 -->
          <el-table
            v-loading="loading"
            :data="orders"
            style="width: 100%"
          >
            <el-table-column prop="orderId" label="订单号" width="120">
              <template slot-scope="scope">
                <el-link type="primary" @click="viewOrderDetail(scope.row)">
                  {{ scope.row.orderId }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="flightNumber" label="航班号" width="120" />
            <el-table-column label="航线" width="200">
              <template slot-scope="scope">
                {{ scope.row.departureCity }} - {{ scope.row.arrivalCity }}
              </template>
            </el-table-column>
            <el-table-column prop="departureTime" label="出发时间" width="180">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.departureTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="ticketType" label="机票类型" width="120" />
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="totalAmount" label="金额" width="120">
              <template slot-scope="scope">
                <span class="price">¥{{ scope.row.totalAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.status === 'PENDING'"
                  size="mini"
                  type="primary"
                  @click="handlePayment(scope.row)"
                >
                  去支付
                </el-button>
                <el-button
                  v-if="scope.row.status === 'PENDING'"
                  size="mini"
                  type="danger"
                  @click="handleCancel(scope.row)"
                >
                  取消订单
                </el-button>
                <el-button
                  size="mini"
                  type="info"
                  @click="viewOrderDetail(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑用户信息对话框 -->
    <el-dialog title="编辑个人资料" :visible.sync="showEditDialog" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'UserCenter',
  data() {
    return {
      loading: false,
      userInfo: {},
      defaultAvatar: require('@/assets/avatar.jpg'),
      orderStats: {},
      orders: [],
      orderStatus: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      showEditDialog: false,
      editForm: {
        username: '',
        email: '',
        phone: ''
      },
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchUserInfo()
    this.fetchOrderStats()
    this.fetchOrders()
  },
  methods: {
    async fetchUserInfo() {
      try {
        const response = await axios.get('/user/info')
        if (response.data.code === 0) {
          this.userInfo = response.data.data
          this.editForm = { ...response.data.data }
        }
      } catch (error) {
        console.error('Error fetching user info:', error)
      }
    },
    async fetchOrderStats() {
      try {
        const response = await axios.get('/user/order-stats')
        if (response.data.code === 0) {
          this.orderStats = response.data.data
        }
      } catch (error) {
        console.error('Error fetching order stats:', error)
      }
    },
    async fetchOrders() {
      this.loading = true
      try {
        const response = await axios.get('/user/orders', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            status: this.orderStatus
          }
        })
        if (response.data.code === 0) {
          this.orders = response.data.data.list
          this.total = response.data.data.total
        }
      } catch (error) {
        console.error('Error fetching orders:', error)
      } finally {
        this.loading = false
      }
    },
    formatDateTime(datetime) {
      return moment(datetime).format('YYYY-MM-DD HH:mm')
    },
    getOrderStatusType(status) {
      const statusMap = {
        'PENDING': 'warning',
        'PAID': 'success',
        'COMPLETED': 'success',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    },
    getOrderStatusText(status) {
      const statusMap = {
        'PENDING': '待支付',
        'PAID': '已支付',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    },
    handleStatusChange() {
      this.currentPage = 1
      this.fetchOrders()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrders()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchOrders()
    },
    handlePayment(order) {
      this.$router.push({
        name: 'Payment',
        params: { orderId: order.orderId }
      })
    },
    async handleCancel(order) {
      try {
        await this.$confirm('确定要取消该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await axios.post(`/orders/${order.orderId}/cancel`)
        if (response.data.code === 0) {
          this.$message.success('订单已取消')
          this.fetchOrders()
          this.fetchOrderStats()
        } else {
          this.$message.error(response.data.msg || '取消订单失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('操作失败，请稍后重试')
        }
      }
    },
    viewOrderDetail(order) {
      this.$router.push({
        name: 'OrderDetail',
        params: { id: order.orderId }
      })
    },
    async submitEdit() {
      try {
        await this.$refs.editForm.validate()
        const response = await axios.put('/user/info', this.editForm)
        if (response.data.code === 0) {
          this.$message.success('个人资料已更新')
          this.showEditDialog = false
          this.fetchUserInfo()
        } else {
          this.$message.error(response.data.msg || '更新失败')
        }
      } catch (error) {
        console.error('Error updating user info:', error)
      }
    }
  }
}
</script>

<style scoped>
.user-center {
  padding: 20px;
}

.user-info-card {
  text-align: center;
}

.user-avatar {
  margin: 20px 0;
}

.user-details {
  margin: 20px 0;
}

.user-details h2 {
  margin: 10px 0;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.el-radio-group {
  float: right;
}
</style> 